package com.mh.www.mh_frame.network;

import com.mh.www.mh_frame.app.application.MyApplication;
import com.mh.www.mh_frame.mypersistentcookiejar.ClearableCookieJar;
import com.mh.www.mh_frame.mypersistentcookiejar.PersistentCookieJar;
import com.mh.www.mh_frame.mypersistentcookiejar.cache.SetCookieCache;
import com.mh.www.mh_frame.mypersistentcookiejar.persistence.SharedPrefsCookiePersistor;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by lenovo on 2018/4/18.
 */

public class RetrofitFactory {
    private static RetrofitFactory mRetrofitFactory;
    private static  ApiService mAPIFunction;
    private RetrofitFactory(){
        ClearableCookieJar cookieJar =
                new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(MyApplication.getAppContext()));
        OkHttpClient mOkHttpClient=new OkHttpClient.Builder()
                .connectTimeout(ApiConstants.HTTP_TIME, TimeUnit.SECONDS)//设置连接超时时间
                .readTimeout(ApiConstants.HTTP_TIME, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(ApiConstants.HTTP_TIME, TimeUnit.SECONDS)//设置写入超时时间
//                .addInterceptor(InterceptorUtil.HeaderInterceptor())//添加其他拦截器
                .cookieJar(cookieJar)
                .addInterceptor(InterceptorUtil.LogInterceptor())//添加日志拦截器
                .build();
        Retrofit mRetrofit=new Retrofit.Builder()
                .baseUrl(ApiConstants.BASE_URL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())//添加gson转换器
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//添加rxjava转换器
                .client(mOkHttpClient)
                .build();
        mAPIFunction=mRetrofit.create(ApiService.class);

    }

    public static RetrofitFactory getInstence(){
        if (mRetrofitFactory==null){
            synchronized (RetrofitFactory.class) {
                if (mRetrofitFactory == null)
                    mRetrofitFactory = new RetrofitFactory();
            }

        }
        return mRetrofitFactory;
    }
    public  ApiService API(){
        return mAPIFunction;
    }
}
